package com.infinitegroup.findmystuff.presenters;

import java.util.List;
import java.util.Map;

import android.content.Context;

import com.infinitegroup.findmystuff.models.Account;
import com.infinitegroup.findmystuff.models.AccountLink;
import com.infinitegroup.findmystuff.models.Admin;
import com.infinitegroup.findmystuff.views.AdminHomeView;

public class AdminHomePresenter {
	
	private AdminHomeView view;
	private Admin admin;
	private String adminUsername;
	private List<Map<String,String>> lockedAccounts;
	
	public AdminHomePresenter(AdminHomeView view, String username){
		this.view = view;
		admin = new AccountLink(username, (Context) view);	
	}
	
	/**
	 * Gets locked accounts associated with the username and returns them as a list of maps.
	 * @return List of items (maps).
	 */
	public List<Map<String,String>> getLockedAccountsToDisplay() {
		try{
			lockedAccounts = admin.getLockedAccounts();
			if (lockedAccounts.isEmpty()){
				return null;
			} else {
				return lockedAccounts;
			}
		} catch (Exception e){
			view.displayMessage("Could not fetch locked accounts from database");
			return null;
		}
	}
	
	/**
	 * This method displays welcome message with username. Not quite.
	 */
	public void updateWelcomeMessage(){
		view.updateWelcome(admin.getUsername());
	}

	public String getFirstName() {
		return admin.getFirstName();
	}

	public void handleUnlockClick(String username) {
		try{
			Account account = new AccountLink(username, (Context) this.view);
			String userid = account.getId();
			admin.unlockAccount(userid);
			view.displayMessage("Account successfully unlocked");
			for (Map<String, String> m : this.lockedAccounts){
				if (m.get("username").equals(username)){
					lockedAccounts.remove(m); // basically remove the map/user you just unlocked.
				}
			}
			view.refreshString(lockedAccounts);
		} catch (Exception e){
			view.displayMessage("Errors encountered while connecting to server.");
		}		
	}

	public void handleDeleteClick(String username) {
		try{
			Account account = new AccountLink(username, (Context) this.view);
			String userid = account.getId();
			admin.deleteAccount(userid);
			view.displayMessage("Account deleted");
			for (Map<String, String> m : this.lockedAccounts){
				if (m.get("username").equals(username)){
					lockedAccounts.remove(m);
					}
				}
	                
		} catch (Exception e){
			view.displayMessage("Crap. Errors encountered while connecting to server.");
		}	
	}

	public void handleRegisterClick() {
		view.advanceToAdminRegistration(admin.getUsername());		
	}

}
